<template>
  <div class="h-full">
    <SearchCom
      :searchList="searchConfig"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="table-container">
      <!-- 操作按钮 -->
      <div class="operation-bar">
        <!-- <el-button type="primary" @click="handleAdd">新增商户</el-button> -->
        <el-button type="success" @click="handleSimpleAdd">快速添加</el-button>
      </div>
      
      <el-table :data="tableData" style="width: 100%" border class="cover-table">
        <el-table-column prop="title" label="商家信息" min-width="300">
          <template #default="scope">
            <div class="flex">
              <el-popover placement="right" width="226" trigger="hover">
                <div
                  class="bigImg"
                  :style="{
                    backgroundImage: `url(${scope.row.image})`,
                  }"
                ></div>
                <template #reference>
                  <div
                    class="goodImg"
                    :style="{
                      backgroundImage: `url(${scope.row.image})`,
                    }"
                  ></div>
                </template>
              </el-popover>

              <div class="ml10 flex_fdc_jcsb text-left">
                <div class="color-333333 line-2">{{ scope.row.name }}</div>
                <el-rate v-model="scope.row.score" allow-half disabled/>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="address" label="商家地址" min-width="200" />
        
        <el-table-column prop="contact" label="联系方式" width="120" />
        
        <el-table-column label="配送信息" min-width="200">
          <template #default="scope">
            <div>配送时间: {{ scope.row.deliveryTime }}</div>
            <div v-if="scope.row.deliveryStaff">
              配送员: {{ scope.row.deliveryStaff.name }} ({{ scope.row.deliveryStaff.phone }})
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="营业信息" min-width="180">
          <template #default="scope">
            <el-popover placement="top" width="300" trigger="hover">
              <template #default>
                <div class="intro-popover">
                  <div><strong>商家简介:</strong></div>
                  <div>{{ scope.row.introduction }}</div>
                  <div class="mt10"><strong>营业时间:</strong></div>
                  <div>{{ scope.row.businessHours }}</div>
                  <div class="mt10"><strong>工作时间设置:</strong></div>
                  <div>{{ scope.row.workingHours }}</div>
                  <div class="mt10"><strong>商家相册:</strong></div>
                  <div class="seller-gallery">
                    <div 
                      v-for="(img, index) in scope.row.gallery" 
                      :key="index" 
                      class="gallery-img"
                      :style="{backgroundImage: `url(${img})`}"
                    ></div>
                  </div>
                </div>
              </template>
              <template #reference>
                <el-button link type="primary">查看详情</el-button>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        
        <el-table-column label="商户数据" min-width="240">
          <template #default="scope">
            <div>入驻时间: {{ scope.row.joinTime }}</div>
            <div>订单总金额: {{ scope.row.totalOrderAmount }}元</div>
            <div>退货订单总金额: {{ scope.row.totalRefundAmount }}元</div>
            <div>平台分润总金额: {{ scope.row.totalPlatformProfit }}元</div>
            <div>在售商品数量: {{ scope.row.onSaleProductCount }}个</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除该商户吗？"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 引入编辑/新增商户组件 -->
    <SellerEdit 
      v-model:visible="editDialogVisible"
      :edit-data="currentEditData"
      @submit="handleSubmit"
      @cancel="handleEditCancel"
    />
    
    <!-- 引入简易新增商户组件 -->
    <SimpleSellerEdit
      v-model:visible="simpleEditDialogVisible"
      :edit-data="currentSimpleEditData"
      @submit="handleSimpleSubmit"
      @cancel="handleSimpleEditCancel"
    />
  </div>
</template>
<script setup>
import { ref } from "vue";
import SearchCom from "@/components/SearchCom.vue";
import SellerEdit from "./edit.vue"; // 引入编辑组件
import SimpleSellerEdit from "./simpleEdit.vue"; // 引入简易编辑组件
import { ElMessage, ElMessageBox } from 'element-plus';

const searchConfig = ref([
  {
    label: "商户名称",
    key: "name",
    type: "input",
  },
  {
    label: "商户状态",
    key: "status",
    type: "select",
    options: [
      { label: "正常", value: "1" },
      { label: "禁用", value: "2" },
    ],
  },
  {
    label: "入驻时间",
    key: "joinTime",
    type: "daterange",
    dateType: "daterange",
  },
  {
    label: "联系方式",
    key: "contact",
    type: "input",
  },
]);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 模拟表格数据
const tableData = ref(
  Array.from({ length: 10 }, (_, index) => ({
    id: index + 1,
    name: `商户名称${index + 1}`,
    image: "https://img-lang.55sld.com/channel1langimages/seller/goods/FazXTfI500MzGvRhxTA.jpg?bindId=292",
    score: (Math.random() * 3 + 2).toFixed(1), // 随机2-5的评分
    address: "北京市朝阳区建国路88号",
    contact: `1391234${index.toString().padStart(4, '0')}`,
    deliveryTime: "09:00-21:00",
    deliveryStaff: {
      name: `配送员${index + 1}`,
      phone: `1381234${index.toString().padStart(4, '0')}`,
    },
    introduction: "这是一家专注于提供高品质服务的商家，我们有多年的行业经验，致力于为顾客提供最好的产品和服务。",
    businessHours: "09:00-22:00",
    workingHours: "周一至周日 09:00-22:00",
    gallery: [
      "https://img-lang.55sld.com/channel1langimages/seller/goods/ZScpQ4FYJscQXRSuxtl.png",
      "https://img-lang.55sld.com/channel1langimages/seller/goods/FazXTfI500MzGvRhxTA.jpg",
      "https://img-lang.55sld.com/channel1langimages/seller/goods/ZScpQ4FYJscQXRSuxtl.png",
    ],
    joinTime: `2023-${(index % 12 + 1).toString().padStart(2, '0')}-${(index % 28 + 1).toString().padStart(2, '0')}`,
    totalOrderAmount: (Math.random() * 100000 + 10000).toFixed(2),
    totalRefundAmount: (Math.random() * 5000).toFixed(2),
    totalPlatformProfit: (Math.random() * 20000 + 5000).toFixed(2),
    onSaleProductCount: Math.floor(Math.random() * 200 + 50),
    status: index % 3 === 0 ? "2" : "1", // 大部分为正常状态
  }))
);

// 编辑对话框显示状态
const editDialogVisible = ref(false);
// 当前编辑的数据
const currentEditData = ref(null);

// 简易编辑对话框显示状态
const simpleEditDialogVisible = ref(false);
// 当前简易编辑的数据
const currentSimpleEditData = ref(null);

// 处理搜索
const handleSearch = (formData) => {
  console.log("搜索条件:", formData);
  // 实际项目中这里应该调用API进行搜索
  ElMessage.success('搜索请求已发送');
};

// 处理重置
const handleReset = () => {
  console.log("表单已重置");
  // 重置后可能需要重新加载初始数据
  ElMessage.info('表单已重置');
};

// 新增商户（完整表单）
const handleAdd = () => {
  currentEditData.value = null; // 置空编辑数据，表示新增
  editDialogVisible.value = true; // 显示对话框
};

// 快速添加商户
const handleSimpleAdd = () => {
  currentSimpleEditData.value = null; // 置空编辑数据，表示新增
  simpleEditDialogVisible.value = true; // 显示对话框
};

// 编辑商户
const handleEdit = (row) => {
  currentEditData.value = { ...row }; // 设置当前编辑的数据
  editDialogVisible.value = true; // 显示对话框
};

// 处理编辑取消
const handleEditCancel = () => {
  currentEditData.value = null;
};

// 处理表单提交
const handleSubmit = (formData) => {
  if (currentEditData.value) {
    // 编辑模式
    const index = tableData.value.findIndex(item => item.id === formData.id);
    if (index !== -1) {
      tableData.value[index] = { ...formData };
      ElMessage.success(`商户: ${formData.name} 已更新`);
    }
  } else {
    // 新增模式
    const newId = Math.max(...tableData.value.map(item => item.id), 0) + 1;
    tableData.value.unshift({
      ...formData,
      id: newId
    });
    ElMessage.success(`商户: ${formData.name} 已添加`);
  }
  
  currentEditData.value = null;
};

// 删除商户
const handleDelete = (row) => {
  console.log("删除商户:", row);
  // 实际项目中这里应该调用API进行删除
  const index = tableData.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    tableData.value.splice(index, 1);
    ElMessage.success(`商户: ${row.name} 已删除`);
  }
};

// 处理页码变化
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  // 这里请求对应页的数据
};

// 处理每页数量变化
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  // 这里请求对应数量的数据
};

// 处理简易编辑取消
const handleSimpleEditCancel = () => {
  currentSimpleEditData.value = null;
};

// 处理简易表单提交
const handleSimpleSubmit = (formData) => {
  // 转换简易表单数据为完整商户数据
  const completeData = {
    id: Math.max(...tableData.value.map(item => item.id), 0) + 1,
    name: formData.name,
    image: "https://img-lang.55sld.com/channel1langimages/seller/goods/FazXTfI500MzGvRhxTA.jpg?bindId=292", // 默认图片
    score: 5.0,
    address: formData.regionText || formData.region.join('/'),
    contact: formData.phone,
    deliveryTime: "09:00-21:00", // 默认配送时间
    deliveryStaff: {
      name: formData.contactName,
      phone: formData.phone
    },
    introduction: `${formData.name}是一家新入驻的商户，联系人：${formData.contactName}`,
    businessHours: "09:00-22:00", // 默认营业时间
    workingHours: "周一至周日 09:00-22:00", // 默认工作时间
    gallery: [
      "https://img-lang.55sld.com/channel1langimages/seller/goods/ZScpQ4FYJscQXRSuxtl.png",
    ],
    joinTime: new Date().toISOString().split('T')[0], // 今天的日期
    totalOrderAmount: 0,
    totalRefundAmount: 0,
    totalPlatformProfit: 0,
    onSaleProductCount: 0,
    status: "1", // 默认正常状态
    profitRatio: formData.profitRatio, // 分润比例
  };
  
  // 添加到表格数据中
  tableData.value.unshift(completeData);
  ElMessage.success(`商户: ${formData.name} 已快速添加`);
};
</script>
<style scoped lang="scss">
.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
}

.goodImg {
  display: inline-block;
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  overflow: hidden;
  border: 1px solid #e2e5f6;
  border-radius: 3px;
  background: #f8f8f8;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.bigImg {
  display: inline-block;
  flex-shrink: 0;
  width: 200px;
  height: 200px;
  overflow: hidden;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.ml10 {
  margin-left: 10px;
}

.flex {
  display: flex;
}

.flex_fdc_jcsb {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.text-left {
  text-align: left;
}

.line-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.intro-popover {
  max-height: 400px;
  overflow-y: auto;
}

.seller-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 5px;
}

.gallery-img {
  width: 80px;
  height: 80px;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
}

.mt10 {
  margin-top: 10px;
}

.operation-bar {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
